package com.yanqu.road.server.cmd.tradewar;

import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.logic.bussiness.player.UserPatronsBussiness;
import com.yanqu.road.logic.pb.PatronsPb;
import com.yanqu.road.pb.patrons.PatronsProto;
import com.yanqu.road.pb.tradewar.TradeWarProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.TradeWarConfigMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Cmd(code = Protocol.S_TRADE_WAR_QUERY_ENEMY_PATRONS, desc = "商战查询对手门客信息")
public class TradeWarQueryEnemyPatronsCmd extends AbstractCommand {

    private long enemyUserId;
    private List<UserPatrons> patronsList;
    private BigInteger enemyAbility = BigInteger.ZERO;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        TradeWarProto.TradeWarQueryEnemyPatronsReqMsg reqMsg = TradeWarProto.TradeWarQueryEnemyPatronsReqMsg.parseFrom(packet.getBytes());
        enemyUserId = reqMsg.getEnemyUserId();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        if(enemyUserId > 0){
            GamePlayer enemyPlayer = GamePlayerMgr.getOnlinePlayer(enemyUserId);
            if(null != enemyPlayer){
                patronsList = new ArrayList<>(enemyPlayer.getModule(PatronsModule.class).getUserPatronsMap().values());
            }else {
                patronsList = new ArrayList<>(UserPatronsBussiness.getUserPatronsMap(enemyUserId).values());
            }
        }else {
            patronsList = TradeWarConfigMgr.initNpcPatronList(new ArrayList<>(player.getModule(PatronsModule.class).getUserPatronsMap().values()));
        }
        enemyAbility = PatronsMgr.getPatronsListAbility(patronsList);
    }

    @Override
    public void sendData(GamePlayer player) {
        TradeWarProto.TradeWarQueryEnemyPatronsRespMsg.Builder respMsg = TradeWarProto.TradeWarQueryEnemyPatronsRespMsg.newBuilder();
        respMsg.setRet(ret);
        if(0 == ret){
            for(UserPatrons userPatrons : patronsList){
                PatronsProto.PatronsTempMsg.Builder patronsMsg = PatronsPb.parsePatronsTempMsg(userPatrons);
                respMsg.addEnemyPatronsList(patronsMsg);
            }
            respMsg.setEnemyPatronsAbility(enemyAbility.toString());
        }
        player.sendPacket(Protocol.U_TRADE_WAR_QUERY_ENEMY_PATRONS, respMsg);
    }
}
